package utils

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.com/yumo01/bag/global"
	"gitee.com/yumo01/bag/models"
	"gitee.com/yumo01/bag/pb"
	"github.com/olivere/elastic/v7"
	"strconv"
)

// 同步mysql->es
func SyncEs() error {
	esClient, err := elastic.NewClient(elastic.SetURL("http://"+global.SevConf.Elastic.Host+":"+global.SevConf.Elastic.Port), elastic.SetSniff(false))
	if err != nil {
		return err
	}

	var users []models.Users
	err = global.MysqlDB.Raw("select * from users").Scan(&users).Error
	if err != nil {
		return err
	}

	for _, v := range users {
		_, err = esClient.Index().Index("users").Id(strconv.Itoa(v.Id)).BodyJson(v).Do(context.Background())
		if err != nil {
			return err
		}
	}

	return nil
}

// es查询users
func EsSearch(text string) (error, []*pb.Users) {
	esClient, err := elastic.NewClient(elastic.SetURL("http://"+global.SevConf.Elastic.Host+":"+global.SevConf.Elastic.Port), elastic.SetSniff(false))
	if err != nil {
		return err, nil
	}

	query := elastic.NewMultiMatchQuery(text, "Username")
	sr, err := esClient.Search("users").Query(query).Do(context.Background())
	if err != nil {
		fmt.Println("es查询失败")
		return err, nil
	}

	var users []*pb.Users
	var u pb.Users
	for _, hit := range sr.Hits.Hits {
		err = json.Unmarshal(hit.Source, &u)
		if err != nil {
			return err, nil
		}
		users = append(users, &u)
	}

	return nil, users
}
